package cn.xtits.xtf.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * Created by ShengHaiJiang on 2017/4/10.
 */
public class JsonUtil {

    public static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static <T> T fromJson(String json, Class<T> t) {

        if (StringUtils.isBlank(json)) {
            return null;
        }
        return gson.fromJson(json, t);
    }

    public static <T> List<T> fromJson(String json, Type t) {

        if (StringUtils.isBlank(json)) {
            return null;
        }
        return gson.fromJson(json, t);
    }

    public static <T> List<T> fromList(String gsonString, Class<T> t) {
        List<T> list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
            }.getType());
        }
        return list;
    }

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> List<Map<String, T>> fromListMaps(String gsonString) {
        List<Map<String, T>> list = null;
        if (gson != null) {
            list = gson.fromJson(gsonString,
                    new TypeToken<List<Map<String, T>>>() {
                    }.getType());
        }
        return list;
    }

    public static <T> Map<String, T> fromMaps(String gsonString) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }
}
